<!DOCTYPE html>
<html lang="zh" class="no-js">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="description" content="book">
<meta name="generator" content="Paradox, paradox-material-theme=0.6.0, mkdocs-material=3.0.3">

<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="">
<meta name="lang:search.pipeline.stopwords" content="true">
<meta name="lang:search.pipeline.trimmer" content="true">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">


<meta name="description" content="book">
<link rel="shortcut icon" href="../assets/images/favicon.png">
<title>JSON · Scala Web 开发——基于Akka HTTP</title>
<link rel="stylesheet" href="../assets/stylesheets/application.451f80e5.css">
<link rel="stylesheet" href="../assets/stylesheets/application-palette.22915126.css">
<meta name="theme-color" content="#009688" />
<link rel="stylesheet" href="../lib/material__tabs/dist/mdc.tabs.min.css">
<link rel="stylesheet" href="../lib/prettify/prettify.css">
<script src="../assets/javascripts/modernizr.1aa3b519.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,700|Roboto+Mono">
<style>
body,input{font-family:"Roboto","Helvetica Neue",Helvetica,Arial,sans-serif}
code,kbd,pre{font-family:"Roboto Mono","Courier New",Courier,monospace}
</style>
<link rel="stylesheet" href="../assets/fonts/font-awesome.css">
<link rel="stylesheet" href="../assets/fonts/material-icons.css">
<link rel="stylesheet" href="../assets/stylesheets/paradox-material-theme.css">
</head>
<body
data-md-color-primary="teal"
data-md-color-accent="indigo"
>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer" autocomplete="off">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search" autocomplete="off">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="Scala Web 开发——基于Akka HTTP" class="md-header-nav__button md-logo">
<i class="md-icon">local_library</i>
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">
Scala Web 开发——基于Akka HTTP
</span>
<span class="md-header-nav__topic">
JSON
</span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" name="search">
<input type="text" class="md-search__input" name="query" placeholder="Search" autocapitalize="off" autocorrect="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">&#xE5CD;</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>

</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/yangbajing/scala-web-development"
title="Go to repository"
class="md-source"
data-md-source="github">
<div class="md-source__icon">
<i class="fa fa-github"></i>
</div>
<div class="md-source__repository">
yangbajing/scala-web-development
</div>
</a>

</div>
</div>
</div>
</nav>
</header>

<div class="md-container">
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0" style="visibility: hidden">
<label class="md-nav__title md-nav__title--site" for="drawer">
<a href="../index.html" title="Scala Web 开发——基于Akka HTTP" class="md-nav__button md-logo">
<span class="md-nav__button md-logo">
<i class="md-icon">local_library</i>
</a>
<a href="../index.html" title="Scala Web 开发——基于Akka HTTP">
Scala Web 开发——基于Akka HTTP
</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/yangbajing/scala-web-development"
title="Go to repository"
class="md-source"
data-md-source="github">
<div class="md-source__icon">
<i class="fa fa-github"></i>
</div>
<div class="md-source__repository">
yangbajing/scala-web-development
</div>
</a>

</div>
<ul>
  <li><a href="../preface.html" class="page">前言</a></li>
  <li><a href="../env/index.html" class="page">Scala 环境配置</a>
  <ul>
    <li><a href="../env/env.1.html" class="page">Sbt</a></li>
    <li><a href="../env/env.2.html" class="page">IDE开发工具</a></li>
    <li><a href="../env/env.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../scala/index.html" class="page">Scala 语言基础</a>
  <ul>
    <li><a href="../scala/scala.0.html" class="page">REPL</a></li>
    <li><a href="../scala/scala.1.html" class="page">你好，Scala</a></li>
    <li><a href="../scala/scala.2.html" class="page">Scala基础</a></li>
    <li><a href="../scala/scala.3.html" class="page">流程和函数</a></li>
    <li><a href="../scala/scala.4.html" class="page">集合</a></li>
    <li><a href="../scala/scala.5.html" class="page">class和object</a></li>
    <li><a href="../scala/scala.6.html" class="page">函数式</a></li>
    <li><a href="../scala/scala.7.html" class="page">Trait</a></li>
    <li><a href="../scala/scala.8.html" class="page">并发</a></li>
    <li><a href="../scala/scala.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../basic/index.html" class="page">Akka HTTP 基础</a>
  <ul>
    <li><a href="../basic/basic.0.html" class="page">Akka HTTP 基础</a></li>
    <li><a href="../basic/basic.1.html" class="page">Web 工作方式</a></li>
    <li><a href="../basic/basic.2.html" class="page">使用 Akka Http 搭建一个简单的 Web 服务</a></li>
    <li><a href="../basic/basic.3.html" class="page">Akka HTTP 的通用抽象</a></li>
    <li><a href="../basic/basic.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../server-api/index.html" class="page">服务端API</a>
  <ul>
    <li><a href="../server-api/work.html" class="page">Akka HTTP 如何使得 Web 工作</a></li>
    <li><a href="../server-api/advanced.html" class="page">高级服务端 API</a></li>
  </ul></li>
  <li><a href="../routing-dsl/index.html" class="page">路由DSL</a>
  <ul>
    <li><a href="../routing-dsl/route.html" class="page">Route 路由</a></li>
    <li><a href="../routing-dsl/directive.html" class="page">Directive 指令</a></li>
    <li><a href="../routing-dsl/custom-directive.html" class="page">自定义指令</a></li>
    <li><a href="../routing-dsl/rejections.html" class="page">拒绝 rejections</a></li>
    <li><a href="../routing-dsl/exception.html" class="page">异常处理</a></li>
    <li><a href="../routing-dsl/file-upload.html" class="page">实战：大文件断点上传、下载和秒传</a></li>
  </ul></li>
  <li><a href="../directives/index.html" class="page">常用指令</a>
  <ul>
    <li><a href="../directives/path.html" class="page">PathDirectives（路径指令）</a></li>
    <li><a href="../directives/method.html" class="page">directives/method.html</a></li>
    <li><a href="../directives/parameter_form.html" class="page">directives/parameter_form.html</a></li>
    <li><a href="../directives/marshalling.html" class="page">directives/marshalling.html</a></li>
    <li><a href="../directives/file.html" class="page">directives/file.html</a></li>
    <li><a href="../directives/cookie.html" class="page">directives/cookie.html</a></li>
  </ul></li>
  <li><a href="../data/index.html" class="page">数据</a>
  <ul>
    <li><a href="../data/data.0.html" class="page">数据</a></li>
    <li><a href="../data/data.1.html" class="active page">JSON</a></li>
    <li><a href="../data/data.ant-design-pro.html" class="page">实战：为Ant Design Pro提供后端接口</a></li>
    <li><a href="../data/data.kryo.html" class="page">Kryo</a></li>
    <li><a href="../data/data.2.html" class="page">Protobuf</a></li>
    <li><a href="../data/data.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../test/index.html" class="page">测试</a>
  <ul>
    <li><a href="../test/test.0.html" class="page">测试</a></li>
    <li><a href="../test/test.1.html" class="page">Scalatest</a></li>
    <li><a href="../test/test.2.html" class="page">测试异步代码</a></li>
    <li><a href="../test/test.3.html" class="page">端到端测试Route</a></li>
    <li><a href="../test/test.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../actor/index.html" class="page">Akka Actor</a>
  <ul>
    <li><a href="../actor/actor.html" class="page">Akka Typed Actor</a></li>
    <li><a href="../actor/actor-test.html" class="page">Akka Actor 测试</a></li>
    <li><a href="../actor/actor.z.html" class="page">Actor小结</a></li>
  </ul></li>
  <li><a href="../oauth/index.html" class="page">实战：实现OAuth 2服务</a>
  <ul>
    <li><a href="../oauth/oauth.0.html" class="page">实战：OAuth 2 服务</a></li>
    <li><a href="../oauth/oauth.1.html" class="page">OAuth 2简介</a></li>
    <li><a href="../oauth/oauth.2.html" class="page">OAuth 2接口设计</a></li>
    <li><a href="../oauth/oauth.3.html" class="page">OAuth 2服务实现</a></li>
    <li><a href="../oauth/oauth.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../database/index.html" class="page">访问数据库</a>
  <ul>
    <li><a href="../database/database.0.html" class="page">访问数据库</a></li>
    <li><a href="../database/database.1.html" class="page">使用 JDBC 访问 PostgreSQL</a></li>
    <li><a href="../database/database.2.html" class="page">使用 Slick 访问数据库</a></li>
    <li><a href="../database/database.3.html" class="page">访问 Cassandra 数据库</a></li>
    <li><a href="../database/database.4.html" class="page">访问 Redis</a></li>
    <li><a href="../database/database.5.html" class="page">访问 Elasticsearch</a></li>
    <li><a href="../database/database.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../engineering/index.html" class="page">工程化</a>
  <ul>
    <li><a href="../engineering/swagger.html" class="page">使用Swagger编写API文档</a></li>
    <li><a href="../engineering/guice.html" class="page">使用Guice管理类依赖</a></li>
  </ul></li>
  <li><a href="../grpc/index.html" class="page">Akka gRPC</a>
  <ul>
    <li><a href="../grpc/grpc.html" class="page">gRPC服务</a></li>
    <li><a href="../grpc/build-tool.html" class="page">构建工具</a></li>
    <li><a href="../grpc/deployment.html" class="page">部署</a></li>
    <li><a href="../grpc/grpc.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../config-discovery/index.html" class="page">实战：配置管理、服务发现系统</a></li>
  <li><a href="../appendix/index.html" class="page">附录</a>
  <ul>
    <li><a href="../appendix/appendix.0.html" class="page">参考资料</a></li>
    <li><a href="../appendix/appendix.1.html" class="page">专业术语</a></li>
    <li><a href="../appendix/appendix.2.html" class="page">词汇表</a></li>
  </ul></li>
  <li><a href="../donate.html" class="page">赞助</a></li>
</ul>
<nav class="md-nav md-nav--secondary">
<label class="md-nav__title" for="__toc">Table of contents</label>
<ul>
  <li><a href="../data/data.1.html#json" class="header">JSON</a>
  <ul>
    <li><a href="../data/data.1.html#jackson" class="header">Jackson</a></li>
    <li><a href="../data/data.1.html#jacksonsupport" class="header">JacksonSupport</a></li>
    <li><a href="../data/data.1.html#在-routing-dsl-里使用" class="header">在 routing DSL 里使用</a></li>
    <li><a href="../data/data.1.html#总结" class="header">总结</a></li>
  </ul></li>
</ul>
</nav>

</nav>
<ul style="display: none">
<li class="md-nav__item md-version" id="project.version">
<label class="md-nav__link" for="__version">
<i class="md-icon" title="Version">label_outline</i> 1.0.0
</label>
</li>
</ul>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<label class="md-nav__title" for="__toc">Table of contents</label>
<ul>
  <li><a href="../data/data.1.html#json" class="header">JSON</a>
  <ul>
    <li><a href="../data/data.1.html#jackson" class="header">Jackson</a></li>
    <li><a href="../data/data.1.html#jacksonsupport" class="header">JacksonSupport</a></li>
    <li><a href="../data/data.1.html#在-routing-dsl-里使用" class="header">在 routing DSL 里使用</a></li>
    <li><a href="../data/data.1.html#总结" class="header">总结</a></li>
  </ul></li>
</ul>
</nav>

</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset">
<div class="md-content__searchable">
<h1><a href="#json" name="json" class="anchor"><span class="anchor-link"></span></a>JSON</h1>
<h2><a href="#jackson" name="jackson" class="anchor"><span class="anchor-link"></span></a>Jackson</h2>
<p><strong>Jackson</strong> 是Java生态圈里最流行的JSON序列化库，它的官方网站是：<a href="https://github.com/FasterXML/jackson">https://github.com/FasterXML/jackson</a>。</p><div class="callout note "><div class="callout-title">为什么选择 Jackson</div>
<p>为什么选择 Jackson 而不是更Scala范的 <strong>play-json</strong>、 <strong>circe</strong>、 <strong>json4s</strong> 等JSON序列化库呢？这里主要考虑是 Jackson 在Java生态圈里更流行，相对熟悉的人更多，可以一定程度上减轻Javaer们使用Scala时上手的难度。 同时，Jackson支持对大部分Java和Scala下的集合库、数据类型的JSON序列化，而大部分Scala范的JSON库只支持Scala的集合库、case class和数据类型。当你的应用里同时使用Java和Scala两种不同的集合类型和Java style class与Scala case class时，Jackson都可以对其完美支持。</p></div>
<h2><a href="#jacksonsupport" name="jacksonsupport" class="anchor"><span class="anchor-link"></span></a>JacksonSupport</h2>
<p>基于 Akka HTTP 的 marshal/unmarshal 机制，可以很容易的集成各种序列化/反序列化工具。<a href="https://github.com/hseeberger/akka-http-json">akka-http-json</a> 这套库就提供了9种不同的JSON序列化/反序列化方安供用户选择。</p>
<p>我们需要在 sbt 里添加依赖：</p>
<pre class="prettyprint"><code class="language-scala">libraryDependencies += &quot;de.heikoseeberger&quot; %% &quot;akka-http-jackson&quot; % &quot;1.22.0&quot;
</code></pre>
<h3><a href="#使用默认的-akka-http-jackson" name="使用默认的-akka-http-jackson" class="anchor"><span class="anchor-link"></span></a>使用默认的 akka-http-jackson</h3>
<pre class="prettyprint"><a class="icon go-to-source" href="https://github.com/yangbajing/scala-web-development/tree/master/data/src/test/scala/scalaweb/data/json/jackson/JacksonSupportTest.scala#L24-L50" target="_blank" title="Go to snippet source"></a><code class="language-scala">&quot;Default ObjectMapper&quot; should {
  import de.heikoseeberger.akkahttpjackson.JacksonSupport._

  &quot;从case class序列化和反序列化&quot; in {
    val foo = Foo(&quot;bar&quot;, 2018)
    val result =
      Marshal(foo).to[RequestEntity].flatMap(Unmarshal(_).to[Foo]).futureValue
    foo shouldBe result
  }

  &quot;从数组case class序列化和反序列化&quot; in {
    val foos = Seq(Foo(&quot;bar&quot;, 2018))
    val result = Marshal(foos)
      .to[RequestEntity]
      .flatMap(Unmarshal(_).to[Seq[Foo]])
      .futureValue
    foos shouldBe result
  }

  &quot;不支持OffsetDateTime&quot; in {
    val foo = FooTime(&quot;羊八井&quot;, OffsetDateTime.now())
    val requestEntity = Marshal(foo).to[RequestEntity].futureValue
    intercept[MismatchedInputException] {
      throw Unmarshal(requestEntity).to[Foo].failed.futureValue
    }
  }
}</code></pre>
<p>可以看到，默认的 akka-http-jackson 不支持 Java 8 新提供的时间/日期类型序列化，这是因为它默认使用的 Jackson ObjectMapper 没有加载 <strong>JavaTimeModule</strong> 这个模块在 <a href="https://github.com/FasterXML/jackson-modules-java8/tree/master/datetime">https://github.com/FasterXML/jackson-modules-java8/tree/master/datetime</a> 可以找到JavaTimeModule这个模块的更多详细说明。</p>
<pre class="prettyprint"><code class="language-scala">/**
  * Automatic to and from JSON marshalling/unmarshalling usung an in-scope Jackon&#39;s ObjectMapper
  */
object JacksonSupport extends JacksonSupport {

  val defaultObjectMapper: ObjectMapper =
    new ObjectMapper().registerModule(DefaultScalaModule)
}
</code></pre>
<h3><a href="#通过隐式值使用自定义的-objectmapper" name="通过隐式值使用自定义的-objectmapper" class="anchor"><span class="anchor-link"></span></a>通过隐式值使用自定义的 ObjectMapper</h3>
<p>首先来看看 akka-http-jackson 定义的 <a href="https://github.com/hseeberger/akka-http-json/blob/master/akka-http-jackson/src/main/scala/de/heikoseeberger/akkahttpjackson/JacksonSupport.scala">JacksonSupport.scala</a>，它通过两个隐式函数实现了 Akka HTTP 的 Marshal/Unmarshal 功能。</p>
<pre class="prettyprint"><code class="language-scala">  /**
    * HTTP entity =&gt; `A`
    */
  implicit def unmarshaller[A](
      implicit ct: TypeTag[A],
      objectMapper: ObjectMapper = defaultObjectMapper
  ): FromEntityUnmarshaller[A] =
    jsonStringUnmarshaller.map(
      data =&gt; objectMapper.readValue(data, typeReference[A]).asInstanceOf[A]
    )

  /**
    * `A` =&gt; HTTP entity
    */
  implicit def marshaller[Object](
      implicit objectMapper: ObjectMapper = defaultObjectMapper
  ): ToEntityMarshaller[Object] =
    Jackson.marshaller[Object](objectMapper)
</code></pre>
<p>可以看到隐式函数又分别定义了两个和一个隐式参数，而 <code>objectMapper: ObjectMapper = defaultObjectMaper</code>这个隐式参数定义了默认值，这样在使用时我们就可以提供自定义的 ObjectMapper 来替代默认的 <code>defaultObjectMapper</code>。先来看看怎样使用自定义的 ObjectMapper：</p>
<pre class="prettyprint"><a class="icon go-to-source" href="https://github.com/yangbajing/scala-web-development/tree/master/data/src/test/scala/scalaweb/data/json/jackson/JacksonSupportTest.scala#L54-L75" target="_blank" title="Go to snippet source"></a><code class="language-scala">&quot;Custom ObjectMapper&quot; should {
  import de.heikoseeberger.akkahttpjackson.JacksonSupport._
  implicit val objectMapper: ObjectMapper =
    helloscala.common.json.Jackson.defaultObjectMapper

  &quot;支持OffsetDateTime&quot; in {
    val foo = FooTime(&quot;羊八井&quot;, OffsetDateTime.now())
    val requestEntity = Marshal(foo).to[RequestEntity].futureValue
    val result = Unmarshal(requestEntity).to[FooTime].futureValue
    foo shouldBe result
  }

  &quot;从数组case class序列化和反序列化&quot; in {
    val foos = Seq(FooTime(&quot;羊八井&quot;, OffsetDateTime.now()))
    val results =
      Marshal(foos)
        .to[RequestEntity]
        .flatMap(Unmarshal(_).to[Seq[FooTime]])
        .futureValue
    foos shouldBe results
  }
}</code></pre>
<p>通过在代码上下文中定义一个隐式值：<code>implicit val objectMapper: ObjectMapper = ....</code> <em>（变量名可以取任何名字，不需要是<code>objectMapper</code>。但是需要保证在代码上下文中只有一个ObjectMapper隐式类型。）</em>，Scala 编译器在编译代码时将使用定义的隐式值传入函数 <code>unmarshaller</code> 或 <code>marshaller</code> 中以替代函数定义时设置的默认值。</p>
<p>自定义 ObjectMapper 定义在object <a href="https://github.com/yangbajing/scala-web-development/tree/master/common/src/main/scala/helloscala/common/json/Jackson.scala">Jackson.scala</a>：</p>
<pre class="prettyprint"><a class="icon go-to-source" href="https://github.com/yangbajing/scala-web-development/tree/master/common/src/main/scala/helloscala/common/json/Jackson.scala#L30-L58" target="_blank" title="Go to snippet source"></a><code class="language-scala">implicit val defaultObjectMapper: ObjectMapper = getObjectMapper

private def getObjectMapper: ObjectMapper = {
  new ObjectMapper()
  val FILTER_ID_CLASS: Class[GeneratedMessage] = classOf[GeneratedMessage]
  new ObjectMapper()
    .setFilterProvider(new SimpleFilterProvider().addFilter(
      FILTER_ID_CLASS.getName,
      SimpleBeanPropertyFilter.serializeAllExcept(&quot;allFields&quot;)))
    .setAnnotationIntrospector(new JacksonAnnotationIntrospector() {
      override def findFilterId(a: Annotated): AnyRef =
        if (FILTER_ID_CLASS.isAssignableFrom(a.getRawType))
          FILTER_ID_CLASS.getName
        else super.findFilterId(a)
    })
    .findAndRegisterModules
    //.setDateFormat(new SimpleDateFormat(&quot;yyyy-MM-dd HH:mm:ss&quot;))
    //.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY)
    .enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES)
    .enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES)
    .enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
    .enable(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS)
    .disable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES)
    .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
    .disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE) // 禁止反序列化时将时区转换为 Z
    .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) // 允许序列化空的对象
    .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) // 日期时间类型不序列化成时间戳
    .disable(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS) // 日期时间类型不序列化成时间戳
    .setSerializationInclusion(JsonInclude.Include.NON_NULL) // 序列化时不包含null的键</code></pre>
<h3><a href="#自定义反序列化时允许的mediatype类型" name="自定义反序列化时允许的mediatype类型" class="anchor"><span class="anchor-link"></span></a>自定义反序列化时允许的MediaType类型</h3>
<p>默认情况下，JacksonSupport要求客户端提交的HTTP请求必需设置Content-Type的mime-type类型为：<code>application/json</code>，但很多时候会遇到不那么规范的客户端，它们并未正确的设置HTTP请求头。这时我们可以自定义JacksonSupport让它在反序列化时支持其它Content-Type：这里定义除了<code>application/json</code>外还支持<code>text/plain</code>类型的请求。</p>
<pre class="prettyprint"><a class="icon go-to-source" href="https://github.com/yangbajing/scala-web-development/tree/master/data/src/test/scala/scalaweb/data/json/jackson/JacksonSupportTest.scala#L79-L101" target="_blank" title="Go to snippet source"></a><code class="language-scala">&quot;Custom unmarshallerContentTypes&quot; should {
  final object CustomJacksonSupport extends JacksonSupport {
    override def unmarshallerContentTypes: immutable.Seq[ContentTypeRange] =
      List(MediaTypes.`text/plain`, MediaTypes.`application/json`)
  }

  &quot;text/plain unmarshal failed&quot; in {
    import de.heikoseeberger.akkahttpjackson.JacksonSupport._
    val entity = HttpEntity(&quot;&quot;&quot;{&quot;name&quot;: &quot;羊八井&quot;, &quot;since&quot;: 2018}&quot;&quot;&quot;)
    entity.contentType.mediaType shouldBe MediaTypes.`text/plain`
    intercept[UnsupportedContentTypeException] {
      throw Unmarshal(entity).to[Foo].failed.futureValue
    }
  }

  &quot;text/plain unmarshal&quot; in {
    import CustomJacksonSupport._
    val entity = HttpEntity(&quot;&quot;&quot;{&quot;name&quot;: &quot;羊八井&quot;, &quot;since&quot;: 2018}&quot;&quot;&quot;)
    entity.contentType.mediaType shouldBe MediaTypes.`text/plain`
    val foo = Unmarshal(entity).to[Foo].futureValue
    foo shouldBe Foo(&quot;羊八井&quot;, 2018)
  }
}</code></pre>
<h2><a href="#在-routing-dsl-里使用" name="在-routing-dsl-里使用" class="anchor"><span class="anchor-link"></span></a>在 routing DSL 里使用</h2>
<p>在 Akka HTTP Routing DSL 里使用Jackson来反序列化/序列化JSON就非常简单了。通过<code>entity(as[FooTime])</code>指令来将提交的JSON数据解析成 <code>FooTime</code> 样本类（将调用 <code>unmarshaller[A]</code> 隐式函数），在<code>complete</code>函数响应结果时将 <code>FooTime</code> 对象序列化成JSON字符串并设置对应的Content-Type（调用 <code>marshaller[A]</code> 隐式函数）。</p>
<pre class="prettyprint"><a class="icon go-to-source" href="https://github.com/yangbajing/scala-web-development/tree/master/data/src/test/scala/scalaweb/data/json/jackson/JacksonSupportTest.scala#L105-L129" target="_blank" title="Go to snippet source"></a><code class="language-scala">&quot;routing-dsl&quot; should {
  import akka.http.scaladsl.server.Directives._
  import de.heikoseeberger.akkahttpjackson.JacksonSupport._
  implicit val objectMapper: ObjectMapper =
    helloscala.common.json.Jackson.defaultObjectMapper

  val route: Route = path(&quot;api&quot;) {
    post {
      entity(as[FooTime]) { foo =&gt;
        complete(foo.copy(since = foo.since.plusYears(1)))
      }
    }
  }

  &quot;post json&quot; in {
    val foo = FooTime(&quot;羊八井&quot;, OffsetDateTime.now())
    Post(&quot;/api&quot;, foo) ~&gt; route ~&gt; check {
      status shouldBe StatusCodes.OK
      contentType.mediaType shouldBe MediaTypes.`application/json`
      val payload = responseAs[FooTime]
      foo.name shouldBe payload.name
      foo.since.isBefore(payload.since) shouldBe true
    }
  }
}</code></pre>
<h2><a href="#总结" name="总结" class="anchor"><span class="anchor-link"></span></a>总结</h2>
<p>Akka HTTP通过强大的 Marshal/Unmarshal 机制来实现数据的序列/反序列化，作为一款工具库 Akka HTTP 提供了足够的灵活性，用户可以选择自己喜欢的序列/反序列化工具和使用方式。对于JSON，推荐从 <strong><a href="https://github.com/hseeberger/akka-http-json">https://github.com/hseeberger/akka-http-json</a></strong> 开始，上面很有可能找到你想要的。同时，akka-http-json也是一个不错的学习 Akka HTTP Marshal/Unmarshal 机制的样例。</p>
<p>完整的测试代码在：<a href="https://github.com/yangbajing/scala-web-development/tree/master/data/src/test/scala/scalaweb/data/json/jackson/JacksonSupportTest.scala">data/src/test/scala/scalaweb/data/json/jackson/JacksonSupportTest.scala</a>，可以通过以下命令来运行它：</p>
<pre class="prettyprint"><code class="language-scala">sbt &quot;data/testOnly scalaweb.data.json.jackson.JacksonSupportTest&quot;
</code></pre>
<p><em>测试结果示例：</em> <img src="../assets/imgs/json/JacksonSupportTest.png" /></p>
</div>
<div>
<a href="https://github.com/yangbajing/scala-web-development/tree/master/book/src/main/paradox/data/data.1.md" title="Edit this page" class="md-source-file md-edit">
Edit this page
</a>
</div>
<div class="print-only">
<span class="md-source-file md-version">
1.0.0
</span>
</div>
</article>
</div>
</div>
</main>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="../data/data.0.html" title="数据" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span class="md-footer-nav__direction">
Previous
</span>
数据
</span>
</div>
</a>
<a href="../data/data.ant-design-pro.html" title="实战：为Ant Design Pro提供后端接口" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span class="md-footer-nav__direction">
Next
</span>
实战：为Ant Design Pro提供后端接口
</span>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
Powered by
<a href="https://github.com/lightbend/paradox">Paradox</a>
and
<a href="https://jonas.github.io/paradox-material-theme/">Paradox Material Theme</a>

</div>
<div class="md-footer-social">
<a href="https://github.com/yangbajing" class="md-footer-social__link fa fa-github"></a><a href="https://weibo.com/yangbajing" class="md-footer-social__link fa fa-globe"></a><a href="https://www.yangbajing.me/" class="md-footer-social__link fa fa-globe"></a>
</div>

</div>
</div>
</footer>

</div>
<script src="../assets/javascripts/application.583bbe55.js"></script>
<script src="../assets/javascripts/paradox-material-theme.js"></script>
<script>app.initialize({version:"0.17",url:{base:"../."}})</script>
<script type="text/javascript" src="../lib/prettify/prettify.js"></script>
<script type="text/javascript" src="../lib/prettify/lang-scala.js"></script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
window.prettyPrint && prettyPrint();
});
</script>
</body>
</html>
